let _Vue = null

export default class VueRouter {
    constructor (options) {
        this.options = options
        this.routerMap = {}
        this.data = _Vue.observable({
            current: window.location.hash.slice(1) || '/'
        })
    }
    static install (Vue) {
        // 1. 判断插件是否被安装过
        if (VueRouter.install.installed) {
            return 
        }
        VueRouter.install.installed = true

        // 2. 将Vue构造函数记录到全局变量
        _Vue = Vue

        // 3. 把创建Vue实例时传入的router对象注入到Vue实例上
        // 通过混入mixin

        _Vue.mixin({
            beforeCreate() {
                if (this.$options.router) {
                    _Vue.prototype.$router = this.$options.router
                    this.$options.router.init()
                }
            }
        })
    }
    init () {
        this.createRouterMap()
        this.initComponents(_Vue)
        this.intiEvent()
    }
    intiEvent () {
        // history
        // window.addEventListener('popstate', () => {
        //     this.data.current = window.location.pathname
        // })
        
        // hash
        window.addEventListener('popstate', () => {
            this.data.current = window.location.hash.slice(1)
        })
        window.addEventListener('hashchange', () => {
            this.data.current = window.location.hash.slice(1)
        })
    }
    createRouterMap () {
        // 遍历所有路由规则options.routes
        // 将路由规则解析成键值对形式，存储到routerMap中

        this.options.routes.map(route => {
            this.routerMap[route.path] = route.component
        })
    }
    initComponents (Vue) {
        const _this = this
        Vue.component('router-link', {
            props: {
                to: String
            },
            render(h) {
                return h('a', {
                    attrs: {
                        href: `${this.to}`,
                    },
                    on: {
                        click: this.onClick
                    }
                }, [this.$slots.default])
            },            
            methods: {
                onClick (e) {
                    // history.pushState({}, '', this.to)
                    window.location.hash = this.to
                    _this.data.current = this.to
                    e.preventDefault()
                }
            }
        })
        Vue.component('router-view', {            
            render(h) {
                // 获取当前路由地址对应的组件
                const component = _this.routerMap[_this.data.current]
                return h(component)
            }
        })
    }
}